package com.jaks.xpense;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaks.xpense.data.PaymentTypes;
import com.jaks.xpense.data.entities.PaymentType;
import com.jaks.xpense.utils.FlowLayout;
import com.jaks.xpense.utils.Globals;

public class SearchCriteriaActivity extends Activity implements OnClickListener {

	private TextView fromDate;
	private TextView toDate;
	private TextView paidThru;
	private CheckBox includePaymentType;
	private CheckBox categorizeTags;
	private FlowLayout tagsLayout;
	private PaymentTypes paymentTypes;

	private ArrayList<PaymentType> paymentTypesList;
	private long paymentTypeId;
	private long[] selectedTagIds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.search);
		fromDate = (TextView) findViewById(R.id.fromDate);
		toDate = (TextView) findViewById(R.id.toDate);
		paidThru = (TextView) findViewById(R.id.searchPaymentType);
		includePaymentType = (CheckBox) findViewById(R.id.includePaymentType);
		categorizeTags = (CheckBox) findViewById(R.id.categorizeTags);
		tagsLayout = (FlowLayout) findViewById(R.id.searchTagsLayout);
		ImageView selectTags = (ImageView) findViewById(R.id.addTags);
		TextView search = (TextView) findViewById(R.id.search);

		fromDate.setOnClickListener(this);
		toDate.setOnClickListener(this);
		paidThru.setOnClickListener(this);
		selectTags.setOnClickListener(this);
		search.setOnClickListener(this);

		registerForContextMenu(paidThru);

		paymentTypeId = 0;
		paymentTypes = new PaymentTypes(this);

		refreshPaymentTypes();
		initDefaults();
	}

	private void initDefaults() {

		if (paymentTypesList.size() > 0) {
			setPaymentType(paymentTypesList.get(0));
		}

		Calendar from = Calendar.getInstance();
		from.set(Calendar.DATE, 1);
		String firstDay = Globals.toDateText(from);

		String today = Globals.toDateText(Calendar.getInstance());
		fromDate.setText(firstDay);
		toDate.setText(today);

		selectedTagIds = null;
		showTagCloud(null);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		paymentTypes.close();
	}

	private void refreshPaymentTypes() {
		paymentTypesList = paymentTypes.readAllToList();
	}

	private void setPaymentType(long id) {

		for (PaymentType type : paymentTypesList) {
			if (type.getId() == id) {
				setPaymentType(type);
				break;
			}
		}
	}

	private void setPaymentType(PaymentType type) {
		paymentTypeId = type.getId();
		paidThru.setText(getString(R.string.paidThru) + " " + type.getName());
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// menu.clear();
		menu.setHeaderTitle(R.string.paymentTypes);
		menu.setHeaderIcon(null);
		for (PaymentType paymentType : paymentTypesList) {
			menu.add(0, (int) paymentType.getId(), 0, paymentType.getName());
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		setPaymentType(item.getItemId());
		return true;
	}

	private final DatePickerDialog.OnDateSetListener fromDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			fromDate.setText(Globals.toDateText(year, month, day));
		}
	};

	private final DatePickerDialog.OnDateSetListener toDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			toDate.setText(Globals.toDateText(year, month, day));
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.fromDate:
				showDatePicker(fromDate, fromDateSetListener);
				break;
			case R.id.toDate:
				showDatePicker(toDate, toDateSetListener);
				break;
			case R.id.searchPaymentType:
				openContextMenu(paidThru);
				break;
			case R.id.addTags:
				selectTags();
				break;
			case R.id.search:
				search();
				break;
		}
	}

	private void showTagCloud(String[] selectedTagNames) {
		tagsLayout.removeAllViews();

		if (selectedTagNames == null)
			selectedTagNames = new String[] { getString(R.string.noTagsSelected) };

		for (int i = 0; i < selectedTagNames.length; i++) {
			tagsLayout.addView(getTagView(selectedTagNames[i]), new FlowLayout.LayoutParams(4, 4));
		}
	}

	private TextView getTagView(String tagName) {
		TextView textView = new TextView(this);
		textView.setText(tagName);
		textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		textView.setPadding(3, 2, 3, 2);
		textView.setTextColor(Color.parseColor(Globals.TagForegroundColor));
		textView.setBackgroundColor(Color.parseColor(Globals.TagBackgroundColor));
		textView.setSingleLine(true);

		return textView;
	}

	private void selectTags() {
		Intent intent = new Intent(this, SelectTagsActivity.class);
		intent.putExtra(Globals.SelectedTagIds, selectedTagIds);
		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK)
			return;

		selectedTagIds = data.getLongArrayExtra(Globals.SelectedTagIds);
		String[] selectedTagNames = data.getStringArrayExtra(Globals.SelectedTagNames);

		showTagCloud(selectedTagNames);
	}

	private void search() {
		String[] dates = new String[] { fromDate.getText().toString(), toDate.getText().toString() };

		Intent intent = null;

		if (categorizeTags.isChecked())
			intent = new Intent(this, FilterByCategoryActivity.class);
		else
			intent = new Intent(this, FilterExpensesActivity.class);

		intent.putExtra("dates", dates);
		intent.putExtra(Globals.SelectedTagIds, selectedTagIds);

		if (includePaymentType.isChecked())
			intent.putExtra("paymentType", paymentTypeId);
		else
			intent.putExtra("paymentType", 0);

		startActivityForResult(intent, 0);
	}

	private void showDatePicker(TextView dateView, DatePickerDialog.OnDateSetListener dateSetListener) {
		Calendar calendar = Globals.toCalendar(dateView.getText().toString());
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog datePicker = new DatePickerDialog(this, dateSetListener, year, month, day);
		datePicker.show();
	}
}
